import Router from "koa-router";
import path from "path";
import fs from "fs";

let router = new Router();

//找到controllers包下的完整路径js文件
function queryAllControllers() {
  let dirPath = path.resolve("./"); //当前根目录的绝对路径
  let controllerPath = `${dirPath}/controllers`; //controllers的绝对路径
  let allFiles = fs.readdirSync(controllerPath); //controllers包下的所有文件
  //过滤并找出所有的js文件并拼接文件协议以及完整路径
  let allControllerfiles = allFiles
    .filter((file) => file.endsWith(".js"))
    .map((file) => `file:///${controllerPath}/${file}`);
  return allControllerfiles;
}

//注册路由方法
function registryRouter(controllersJs) {
  //遍历控制器js文件
  controllersJs.forEach(async (file) => {
    //导入控制器的js文件
    let { blogs } = await import(file);
    //遍历导入进来的对象并进行处理，用来注册路由
    for (let item in blogs) {
      let reqArr = item.split(" ");
      let reqPath = reqArr[1];
      let reqFn = blogs[item];
      //注册路由
      if (item.startsWith("get")) {
        router.get(reqPath, reqFn);
      }
    }
  });
}

let jsFiles = queryAllControllers();
//注册路由
registryRouter(jsFiles);

export default router.routes();
